package com.jiaoshou.excel.ssh;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.ssh.ChannelType;
import cn.hutool.extra.ssh.JschRuntimeException;
import cn.hutool.extra.ssh.JschUtil;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;

/**
 * 作者 CG
 * 时间 2021/1/7 11:26
 * 注释 java 连接liunx shell
 * 执行最后一步exit
 */
public class JschShell extends JschUtil {
    public static String execShell(Session session, String cmd, Charset charset) {
        Channel channel = null;
        InputStream inputStream = null;
        String var6;
        try {
            //打开shell
            channel = session.openChannel(ChannelType.SHELL.getValue());
            PrintStream commander = new PrintStream(channel.getOutputStream(), true);
            //连接
            channel.connect();
            //输入命令
            commander.println(cmd);
            // the important command
            commander.println("exit");
            commander.close();
            //获取输入流
            inputStream = channel.getInputStream();
            //转换为String
            var6 = IoUtil.read(inputStream, charset);
        } catch (IOException var11) {
            throw new IORuntimeException(var11);
        } catch (JSchException var12) {
            throw new JschRuntimeException(var12);
        } finally {
            IoUtil.close(inputStream);
            close(channel);
        }
        return var6;
    }
}
